package com.example.base_kotlin_xml.view

import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base_kotlin_xml.R
import com.example.base_kotlin_xml.databinding.FragmentMqttBinding
import com.example.base_model.socket.ModernMqttManager
import com.example.base_model.socket.MqttConnectionState
import com.example.base_model.socket.MqttMessageWrapper
import com.example.base_model.view.BaseFragment
import dagger.hilt.android.AndroidEntryPoint
import jakarta.inject.Inject
import kotlinx.coroutines.launch

/**
 * @Author: jiangKunKun
 * @CreateDate: 2025/11/24
 * @Description: mqtt
 * @SpittingGrooves:
 */
@AndroidEntryPoint
class MqttFragment : BaseFragment<FragmentMqttBinding>() {
    @Inject
    lateinit var mqttManager: ModernMqttManager
    override fun initObservers() {
        // 启动协程进行连接
        lifecycleScope.launch {
            if (mqttManager.connect()) {
                // 连接成功后订阅主题
                val subscribe = mqttManager.subscribe("auction/1985532554641838082")
                LogUtils.d("自动订阅后 ${subscribe}")

                // 监听消息流
                launch {
                    mqttManager.messageFlow.collect { message ->
                        handleMqttMessage(message)
                    }
                }

                // 监听连接状态
                launch {
                    mqttManager.connectionState.collect { state ->
                        handleConnectionState(state)
                    }
                }
            }
        }
    }

    /**
     * 处理接收到的MQTT消息
     *
     * @param message 接收到的消息包装对象
     */
    private fun handleMqttMessage(message: MqttMessageWrapper) {
        when (message.topic) {
            "auction/1985532554641838082" -> {
                LogUtils.d("获取到的消息: ${message.payload}")
                mBinding.tvMqttReceive.text = message.payload
            }
        }
    }

    /**
     * 处理连接状态变化
     *
     * @param state 当前连接状态
     */
    private fun handleConnectionState(state: MqttConnectionState) {
        when (state) {
            MqttConnectionState.CONNECTED -> {
                ToastUtils.showShort("MQTT已连接")
                LogUtils.d("MQTT已连接")
            }
            MqttConnectionState.DISCONNECTED -> {
                ToastUtils.showShort("MQTT已断开")
                LogUtils.d("MQTT已断开")
            }
            MqttConnectionState.CONNECTING -> {
                ToastUtils.showShort("MQTT正在连接...")
                LogUtils.d("MQTT连接中...")
            }
            MqttConnectionState.RECONNECTING -> {
                ToastUtils.showShort("MQTT正在重连...")
                LogUtils.d("MQTT重连中...")
            }
        }
    }



    override fun initClickEvents() {
        // 订阅
        mBinding.btnMqttSubscribe.setOnClickListener {
            lifecycleScope.launch {
                val subscribe = mqttManager.subscribe("auction/1985532554641838082")
                LogUtils.d("点击订阅后 ${subscribe}")
            }
        }
        // 取消订阅
        mBinding.btnMqttUnsubscribe.setOnClickListener {
            lifecycleScope.launch {
                val unsubscribe = mqttManager.unsubscribe("auction/1985532554641838082")
                LogUtils.d("点击取消订阅后 ${unsubscribe}")
            }
        }
        // 发送消息
        mBinding.btnMqttPublish.setOnClickListener {
            lifecycleScope.launch {
                mqttManager.publish("auction/bid", "{\"bidder\":\"张三\",\"amount\":500}")
            }
        }
    }

    override fun initData() {

    }

    override fun attachLayoutRes(): Int = R.layout.fragment_mqtt

    override fun onDestroy() {
        super.onDestroy()
        // 断开MQTT连接
        mqttManager.disconnect()
    }
}